﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using MySql.Data;
using MySql.Data.MySqlClient;

namespace SerialPortLogger
{
    public class DataLogger
    {
        // TODO: This should be moved to a configuration file.
        private static string connectionString = "server=192.168.0.4;user=test;database=test;port=3306;password=test;";

        static MySqlConnection connection = new MySqlConnection(connectionString);

        // connection method
        public static void OpenConnection()
        {
            try
            {
                Console.WriteLine("Connecting to MySQL...");
                connection.Open();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        // Method to write messages to the database
        public static void LogData(string data, string sensor)
        {
            try
            {
                string query = String.Format("INSERT INTO `test`.`monitor` (`data`, `sensor`) VALUES ('{0}', '{1}');", data, sensor);

                MySqlCommand cmd = new MySqlCommand(query, connection);
                // execute the insert query
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Problem executing query: " + ex.ToString());
            }
        }

        // tidy up the connection
        public static void CloseConnection()
        {
            try
            {
                connection.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Problem closing connection: " + ex.ToString());
            }
        }
    }
}
